package it.megasoft78.turingmachine;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FileDialogActivity extends Activity implements
		OnItemClickListener, OnClickListener {
	public static final String START_PATH = "START_PATH";
	public static final String MODE = "MODE";
	public static final int MODE_OPEN_FILE = 1;
	public static final int MODE_SAVE_FILE = 2;
	public static final int MODE_SELECT_FOLDER = 3;
	private static final String ROOT = "/sdcard";
	private String currentPath;
	private int mode;
	private ArrayList<FileDialogItem> items;
	private ListView lstItems;
	private TextView lblCurrentPath;
	private ImageView imgHome;
	private Button btnOpenSave;
	private EditText txtFileName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.file_dialog);

		currentPath = getIntent().getExtras().getString(
				FileDialogActivity.START_PATH);
		mode = getIntent().getExtras().getInt(FileDialogActivity.MODE);

		if (currentPath == null)
			currentPath = FileDialogActivity.ROOT;

		if (mode == 0)
			mode = FileDialogActivity.MODE_OPEN_FILE;

		imgHome = (ImageView) findViewById(R.id.imgHome);
		imgHome.setOnClickListener(this);

		lblCurrentPath = (TextView) findViewById(R.id.lblCurrentPath);
		lblCurrentPath.setOnClickListener(this);

		lstItems = (ListView) findViewById(R.id.lstItems);
		lstItems.setOnItemClickListener(this);

		txtFileName = (EditText) findViewById(R.id.txtFileName);
		btnOpenSave = (Button) findViewById(R.id.btnOpenSave);
		btnOpenSave.setOnClickListener(this);

		if (mode == FileDialogActivity.MODE_OPEN_FILE) {
			btnOpenSave.setText(R.string.lblOpen);
			txtFileName.setEnabled(false);
		} else {
			btnOpenSave.setText(R.string.lblSave);
			txtFileName.setEnabled(true);
		}

		File[] files = getFiles(currentPath);

		this.refreshItems(files);
	}

	private ArrayList<FileDialogItem> getItems(File[] files) {
		ArrayList<FileDialogItem> items = new ArrayList<FileDialogItem>();

		// Check if I need ... to move up in the path
		if (currentPath.compareTo(FileDialogActivity.ROOT) != 0) {
			items.add(new FileDialogItem("...", R.drawable.folder, "", ""));
		}

		for (int t = 0; t < files.length; t++) {
			File f = files[t];

			if (!f.getName().startsWith(".")) {
				int iconResourceId = 0;

				if (f.isDirectory()) {
					iconResourceId = R.drawable.folder;
					items.add(new FileDialogItem(f.getName(), iconResourceId,
							"", this.getLastChangeString(f.lastModified())));
				} else {
					iconResourceId = R.drawable.file;
					items.add(new FileDialogItem(f.getName(), iconResourceId,
							this.getSizeString(f.length()), this
									.getLastChangeString(f.lastModified())));
				}
			}
		}

		Collections.sort(items);

		return items;
	}

	private String getLastChangeString(long lastModified) {
		java.text.DateFormat dateFormat = DateFormat
				.getDateFormat(getApplicationContext());
		return dateFormat.format(new Date(lastModified));
	}

	private String getSizeString(long size) {
		if (size <= 0)
			return "0";

		final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
		int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
		return new DecimalFormat("#,##0.#").format(size
				/ Math.pow(1024, digitGroups))
				+ " " + units[digitGroups];
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (this.mode == FileDialogActivity.MODE_SELECT_FOLDER) {

		} else {
			FileDialogItem item = this.items.get(position);

			if (item.getIconResourceId() == R.drawable.folder) {

				String newPath;

				if (item.getName().compareTo("...") == 0) {
					newPath = currentPath.substring(0,
							currentPath.lastIndexOf('/'));
				} else {
					newPath = currentPath + "/" + item.getName();
				}

				File[] files = getFiles(newPath);

				if (files != null) {
					currentPath = newPath;
					this.refreshItems(files);
				} else {
					Toast.makeText(this, R.string.msgAccessDenied,
							Toast.LENGTH_SHORT).show();
				}
			} else if (item.getIconResourceId() == R.drawable.file) {
				txtFileName.setText(item.getName());
			}
		}
	}

	private File[] getFiles(String path) {
		File fPath = new File(path);
		File[] files = fPath.listFiles();
		return files;
	}

	private void refreshItems(File[] files) {
		lblCurrentPath.setText(currentPath);
		items = this.getItems(files);
		FileDialogAdapter adapter = new FileDialogAdapter(this, items);
		lstItems.setAdapter(adapter);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.imgHome:
		case R.id.lblCurrentPath:
			currentPath = FileDialogActivity.ROOT;
			File[] files = this.getFiles(currentPath);
			this.refreshItems(files);
			break;
			
		case R.id.btnOpenSave:
			Intent resultIntent = new Intent();
			resultIntent.putExtra("FileName", currentPath + "/" + txtFileName.getText().toString());
			setResult(Activity.RESULT_OK, resultIntent);
			this.finish();
			break;
		}
	}
}
